const _ = require("lodash");

// ✅ 终极稳定策略：剔除历史连错 ≥ 5 的号，再挑准确率最高的 32 个号
function select32NumbersByS9(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  const historyMap = {};
  const streakMap = {};

  // 初始化
  allNumbers.forEach((n) => {
    historyMap[n] = [];
    streakMap[n] = { maxWrong: 0, currentWrong: 0 };
  });

  // 遍历历史 temp，记录每个号的“最大连续不中”
  temp.forEach((draw) => {
    const hitNum = draw.number;

    allNumbers.forEach((num) => {
      if (num === hitNum) {
        // 命中：更新最大连错、重置当前错
        streakMap[num].maxWrong = Math.max(streakMap[num].maxWrong, streakMap[num].currentWrong);
        streakMap[num].currentWrong = 0;
      } else {
        streakMap[num].currentWrong += 1;
      }
    });
  });

  // 更新最后一段未命中 streak
  allNumbers.forEach((num) => {
    streakMap[num].maxWrong = Math.max(streakMap[num].maxWrong, streakMap[num].currentWrong);
  });

  // 剔除所有“历史最大连错 ≥ 5” 的号码
  const safeNumbers = allNumbers.filter((num) => streakMap[num].maxWrong < 5);

  // 📈 按照 temp 中的出现频率排序
  const freqMap = _.countBy(temp.map((v) => v.number));
  const sortedSafe = safeNumbers
    .sort((a, b) => (freqMap[b] || 0) - (freqMap[a] || 0))
    .slice(0, 32);

  // 不足 32 个号则补周期短的号
  if (sortedSafe.length < 32) {
    const lastSeen = {};
    for (let i = temp.length - 1; i >= 0; i--) {
      const n = temp[i].number;
      if (!lastSeen[n]) {
        lastSeen[n] = i;
      }
    }
    const backup = allNumbers
      .filter((n) => !sortedSafe.includes(n))
      .sort((a, b) => (lastSeen[a] || 9999) - (lastSeen[b] || 9999))
      .slice(0, 32 - sortedSafe.length);

    return sortedSafe.concat(backup);
  }

  return sortedSafe;
}

module.exports = select32NumbersByS9;
